package com.boshao.classschedule.fragment;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.boshao.classschedule.R;
import com.boshao.classschedule.activity.AlarmActivity;
import com.boshao.classschedule.adapter.MainFragmentAdapter;
import com.boshao.classschedule.model.LifeSchedule;
import com.boshao.classschedule.model.LifeScheduleDao;
import com.boshao.classschedule.utils.TimeUtils;
import com.boshao.classschedule.widget.ActionBarLeft;
import com.boshao.classschedule.widget.ActionBarRight;

/**
 * 添加日程UI的Fragment
 * @author boshao
 *
 */
public class TimeManagerFragment extends AbstartFragment implements OnClickListener{
	public static final String TAG = "time_manager_fragment";
	private View mRootView;
	private EditText mEtActivityName,mEtAdress,mEtDescription;
	private TextView mTvStartDate,mTvStartTime,mTvEndDate,mTvEndTime,
		mTvRepeat,mTvRemind;
	private LifeSchedule mLifeSchedules;
	private CalendarFragment calendarFragment;
	private static final int NEW = 0; 
	private static final int MODIFY = 1; 
	private static int sStyle;
	private int hourOfDay;
	private int minute;
	private int year;
	private int monthOfYear;
	private int dayOfmonth;
	
	public static TimeManagerFragment newInstance(CalendarFragment calendarFragment,LifeSchedule lifeSchedules){
		TimeManagerFragment fragment = new TimeManagerFragment();
		fragment.setLifeSchedules(lifeSchedules);
		fragment.setCalendarFragment(calendarFragment);
		sStyle = MODIFY;
		return fragment;
	}
	
	private void setLifeSchedules(LifeSchedule lifeSchedules) {
		mLifeSchedules = lifeSchedules;
	}
	
	private void setCalendarFragment(CalendarFragment calendarFragment){
		this.calendarFragment = calendarFragment;
	}

	private ViewPager mViewPager;
	public static TimeManagerFragment newInstance(ViewPager viewPager){
		TimeManagerFragment fragment = new TimeManagerFragment();
		sStyle = NEW;
		fragment.setViewPager(viewPager);
		return fragment;
	}
	
	private void setViewPager(ViewPager viewpager){
		mViewPager = viewpager;
	}
	
	@Override
	protected String getFragmentTag() {
		return TAG;
	}

	@Override
	protected int getContentLayoutId() {
		return R.id.rl_time_manager;
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = super.onCreateView(inflater, container, savedInstanceState);
		View delete = view.findViewById(R.id.action_right_one);
		if(sStyle == NEW){
			delete.setVisibility(View.GONE);
		}else{
			delete.setVisibility(View.VISIBLE);
		}
		return view;
	}
	
	@Override
	protected View onAppCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		mRootView = inflater.inflate(R.layout.fragment_time_manager,container,false);
		mEtActivityName = (EditText) mRootView.findViewById(R.id.et_activity_name);
		mEtAdress = (EditText) mRootView.findViewById(R.id.et_adress);
		mEtDescription = (EditText) mRootView.findViewById(R.id.et_ativity_decription);
		mTvStartDate =(TextView) mRootView.findViewById(R.id.et_start_date);
		mTvStartDate.setOnClickListener(this);
		mTvStartTime =(TextView) mRootView.findViewById(R.id.et_start_time);
		mTvStartTime.setOnClickListener(this);
		mTvEndDate =(TextView) mRootView.findViewById(R.id.et_arive_date);
		mTvEndDate.setOnClickListener(this);		
		mTvEndTime =(TextView) mRootView.findViewById(R.id.et_arive_time);
		mTvEndTime.setOnClickListener(this);
		mTvRepeat = (TextView) mRootView.findViewById(R.id.et_ativity_repeat);
		mTvRepeat.setOnClickListener(this);
		mTvRemind = (TextView) mRootView.findViewById(R.id.et_ativity_wake);
		mTvRemind.setOnClickListener(this);
		Calendar calendar = Calendar.getInstance();
		String date = TimeUtils.getFormatDate(TimeUtils.getCurrentYear(),
				TimeUtils.getCurrentMonth(), TimeUtils.getCurrentDay());
		int dayOfweek = TimeUtils.getWeekDay(date);
		mTvStartDate.setText(String.format("%s月%s日 %s",formatTime(TimeUtils.getCurrentMonth()),formatTime(TimeUtils.getCurrentDay()),
				WEEKDAYS[dayOfweek]));
		mTvStartTime.setText(String.format("%s:%s",formatTime(calendar.get(Calendar.HOUR_OF_DAY)),
				formatTime(calendar.get(Calendar.MINUTE))));
		setDataView();
		return mRootView;
	}
	
	private void setDataView() {
		if(mLifeSchedules != null){
			setTextView(mEtActivityName,mLifeSchedules.getActivity_name());
			setTextView(mEtAdress,mLifeSchedules.getAddress());
			setTextView(mEtDescription,mLifeSchedules.getDescription());
			setTextView(mTvStartDate,mLifeSchedules.getStart_date());
			setTextView(mTvEndDate,mLifeSchedules.getEnd_date());
			setTextView(mTvStartTime,mLifeSchedules.getStart_time());
			setTextView(mTvEndTime,mLifeSchedules.getEnd_time());
			setTextView(mTvRepeat,mLifeSchedules.getRepeat());
		}
	}

	private void setTextView(TextView et, String str) {
		if(!TextUtils.isEmpty(str)){
			et.setText(str);
		}else{
			et.setText("");
		}
	}

	@Override
	protected ActionBarLeft getActionBarLeft() {
		return ActionBarLeft.BACK;
	}
	
	@Override
	protected void onClickActionLeft() {
		onBackPressed();
	}
	
	@Override
	protected String getActionBarLeftTitle() {
		return sStyle == NEW ? "创建日程" : "修改日程";
	}
	
	@Override
	protected ActionBarRight getActionBarRight() {
		return ActionBarRight.CHECK;
	}
	
	@Override
	protected void onClickActionRight(int resId) {
		if(resId == R.id.action_right_one){
			deleteTimeManager();
		}else if(resId == R.id.action_right_two){
			saveTimeManager();
		}
	}
	
	

	private String formatDate(String date){
		if(TextUtils.isEmpty(date)){
			return "";
		}
		if(date.length() <= 9 ){
			StringBuilder sb = new StringBuilder();
			sb.append(TimeUtils.getCurrentYear()).append("年");
			sb.append(date);
			return sb.toString();
		}
		return date;
	}

	private void deleteTimeManager() {
		if(sStyle == MODIFY){
			LifeScheduleDao dao = readLifeScheduleDao();
			if(mLifeSchedules != null){
				try{
					dao.delete(mLifeSchedules);
				}catch(Exception e){
				}
				Toast.makeText(getActivity(),"删除日程",Toast.LENGTH_LONG).show();
				if(calendarFragment != null){
					calendarFragment.refrashView();
				}
			}
		}
	}
	
	private void saveTimeManager() {
		if(sStyle == NEW){
			if(isChange()){
				LifeScheduleDao dao = writeLifeScheduleDao();
				String startDate = formatDate(getStartDate());
				String endDate = formatDate(getEndDate());
				LifeSchedule lifeSchedule = new LifeSchedule(null,getActivityName(), 
						startDate,getStartTime(),endDate, 
						getEndTime(),getAddress(),getDescription(),getRepeatText());
				dao.insert(lifeSchedule);
				Toast.makeText(getActivity(),"创建日程成功",Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(getActivity(),"请输入日程名字和开始日期和时间",Toast.LENGTH_LONG).show();
			}
			Fragment f = null;
			if(mViewPager != null){
				f = ((MainFragmentAdapter)mViewPager.getAdapter()).getItem(0);
			}
			if(f != null){
				((CalendarFragment)f).refrashView();
			}
		}else if(sStyle == MODIFY){	
			if(isChange() && mLifeSchedules != null){
				LifeScheduleDao dao = readLifeScheduleDao();
				String startDate = formatDate(getStartDate());
				String endDate = formatDate(getEndDate());
				LifeSchedule lifeSchedule = new LifeSchedule(mLifeSchedules.getId(),getActivityName(), 
						startDate,getStartTime(),endDate, 
						getEndTime(),getAddress(),getDescription(),getRepeatText());
				try{
					dao.update(lifeSchedule);
				}catch(Exception e){
				}
				Toast.makeText(getActivity(),"修改日程成功",Toast.LENGTH_LONG).show();
				
			}else{
				Toast.makeText(getActivity(),"请输入日程名字和开始日期和时间",Toast.LENGTH_LONG).show();
			}
			if(calendarFragment != null){
				calendarFragment.refrashView();
			}
		}
		alarm();
		onBackPressed();
	}
	
	/**
	 * 闹钟
	 */
	private void alarm(){
		AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Service.ALARM_SERVICE);
		Intent intent = new Intent(getActivity(), AlarmActivity.class);
		intent.putExtra("activityName",getActivityName()+","+getDescription());
		//创建PendingIntent对象
		/*
		 * PendingIntent与Intent的区别是PendingIntent处理即将发生的事情
		 * 比如：在通知栏Notification中跳转页面，不是立即跳转
		 * 通常通过  getActivity、getBroadcast、getService得到PendingIntent的实例
		 * 
		 */
		PendingIntent pi = PendingIntent.getActivity(getActivity(), 0, intent, 0);
		Calendar c = Calendar.getInstance();
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH,monthOfYear);
		c.set(Calendar.DAY_OF_MONTH, dayOfmonth);
		c.set(Calendar.HOUR, hourOfDay);
		c.set(Calendar.MINUTE, minute);		
		alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
	}
	
	
	@Override
	protected boolean onBackPressed() {
		hideSoftInput(mRootView.getWindowToken());
		return super.onBackPressed();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.et_start_date:
			showDatePick(v);
			break;
		case R.id.et_start_time:
			showTimePick(v);
			break;
		case R.id.et_arive_date:
			showDatePick(v);
			break;			
		case R.id.et_arive_time:
			showTimePick(v);
			break;			
		case R.id.et_ativity_repeat:
			showRepeatDialog();
			break;			
		case R.id.et_ativity_wake:
			
			break;			
		}
	}
	
	private void showRepeatDialog() {
		RepeatDialogFragment.newInstance(mTvRepeat)
			.show(getFragmentManager(),RepeatDialogFragment.TAG);
	}

	private void showTimePick(View v) {
		Calendar calendar = Calendar.getInstance();
		new TimePickerDialog(getActivity(),new TimeOnDateSetListener(v),
				calendar.get(Calendar.HOUR_OF_DAY),
				calendar.get(Calendar.MINUTE),true)
		.show();
	}

	private void showDatePick(View v) {
		Calendar calendar = Calendar.getInstance();
		DatePickerDialog datePickerDialog = new DatePickerDialog(getActivity(),
				new DateOnDateSetListener(v),
				calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH));
		DatePicker picker = datePickerDialog.getDatePicker();
		picker.setCalendarViewShown(false);
		datePickerDialog.show();
	}


	public static final String[] WEEKDAYS = {"周日","周一","周二","周三","周四","周五","周六"};
	class DateOnDateSetListener implements OnDateSetListener{
		private View v;
		public DateOnDateSetListener(View v) {
			this.v = v;
		}

		@Override
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			TimeManagerFragment.this.year = year;
			TimeManagerFragment.this.monthOfYear = monthOfYear;
			TimeManagerFragment.this.dayOfmonth = dayOfMonth;
			int dayOfWeek = TimeUtils.getWeekDay(TimeUtils.getFormatDate(year,monthOfYear+1,dayOfMonth));
			Calendar c = Calendar.getInstance();
			if(c.get(Calendar.YEAR) == year){
				((TextView)v).setText(String.format("%s月%s日 %s",formatTime(monthOfYear+1),formatTime(dayOfMonth),WEEKDAYS[dayOfWeek]));
			}else{
				((TextView)v).setText(String.format("%d年%d月%d日 %s",year,monthOfYear+1,dayOfMonth,WEEKDAYS[dayOfWeek]));
			}
		}
	}
	
	
	class TimeOnDateSetListener implements OnTimeSetListener{
		private View v;
		public TimeOnDateSetListener(View v) {
			this.v = v;
		}
		
		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			TimeManagerFragment.this.hourOfDay = hourOfDay;
			TimeManagerFragment.this.minute = minute;
			String hour = formatTime(hourOfDay);
			String min = formatTime(minute);
			((TextView)v).setText(String.format("%s:%s",hour,min));
		}
	}
	
	/**
	 *  在number只有1位前补0
	 * @param time
	 * @return
	 */
	private String formatTime(int time){
		StringBuilder sb = new StringBuilder();
		if(sb.append(time).length() == 1){
			sb.delete(0,sb.length());
			sb.append("0").append(time);
		}
		return sb.toString();
	}
	
	public boolean isChange(){
		boolean isRepeated  = !TextUtils.isEmpty(getRepeatText());
		boolean isHasAcivityName = !TextUtils.isEmpty(getActivityName());
		boolean isHasAddress = !TextUtils.isEmpty(getAddress());
		boolean isHasDescription = !TextUtils.isEmpty(getDescription());
		boolean isHasStartDate = !TextUtils.isEmpty(getStartDate());
		boolean isHasStartTime = !TextUtils.isEmpty(getStartTime());
		boolean isHasEndDate = !TextUtils.isEmpty(getEndDate());
		boolean isHasEndTime = !TextUtils.isEmpty(getEndTime());
		boolean isStart = false;
		if(isHasStartDate && isHasStartTime && isHasAcivityName){
			isStart = true;
		}
		return isRepeated || isHasAddress || isHasDescription
				||isHasEndDate || isHasEndTime || isStart;
	}
	
	public String getActivityName(){
		return mEtActivityName.getText().toString();
	}
	public String getAddress(){
		return mEtAdress.getText().toString();
	}
	public String getDescription(){
		return mEtDescription.getText().toString();
	}
	public String getStartDate(){
		return mTvStartDate.getText().toString();
	}
	public String getStartTime(){
		return mTvStartTime.getText().toString();
	}
	public String getEndDate(){
		return mTvEndDate.getText().toString();
	}
	public String getEndTime(){
		return mTvEndTime.getText().toString();
	}
	public String getRepeatText(){
		return mTvRepeat.getText().toString();
	}
}
